import React, { Component } from 'react';
import {high,base,ajax,getMultiLang} from 'nc-lightapp-front';
const { Refer} = high;
import createScript from '../uapRefer.js';
const { NCFormControl: FormControl, NCDatePicker: DatePicker, NCButton: Button, NCRadio: Radio, NCBreadcrumb: Breadcrumb,
    NCRow: Row, NCCol: Col, NCTree: Tree, NCIcon: Icon, NCLoading: Loading, NCTable: Table, NCSelect: Select,
    NCCheckbox: Checkbox, NCNumber, AutoComplete, NCDropdown: Dropdown, NCPanel: Panel,NCModal:Modal,NCForm
} = base;
import './index.less';
import {SelectItem} from '../FormItems';
const {  NCFormItem:FormItem } = NCForm;

  const defaultProps12 = {
    prefixCls: "bee-table",
    multiSelect: {
      type: "checkbox",
      param: "key"
    }
  };

  const format = 'YYYY-MM-DD';
  const timeFormat = 'YYYY-MM-DD HH:mm:ss';
export default class AssidModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json:{},
            showModal:false,
            isShowUnit:false,//是否显示业务单元
            assData: [//辅助核算信息
            ],
            childAssData:[],//接受父组件传过来的参数
            loadData:[],//查询模板加载数据
            listItem:{},//模板数据对应值
            checkedAll:false,
            SelectedAssData:[],//选中的数据
            checkedArray: [
                // false,
                // false,
                // false,
            ],
           // columns10:this.columns10
        };
        this.close = this.close.bind(this);
    }
    componentWillMount(){
		let callback= (json) =>{
            this.setState({
              json:json,
                columns_reportSum:this.columns_reportSum,
				},()=>{
				//initTemplate.call(this, this.props);
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    //字符转换为数组
    strChangetoArr(str){
        if(str.indexOf(',')!=-1){
            return str.split(',');
        }else{
            return [str]
        }
    }
    componentWillReceiveProps (nextProp) {
        /** 
            *父组件传递过来的pretentAssData里包含 
            *   pk_accountingbook,
            *    pk_accasoa,
            *    prepareddate,
            *    pk_org,
            *   assData,
            *   assid,
            *   checkboxShow,是否显示复选框 true、false
            *   checkedAll 是否全选中 true， false
            *   pk_defdoclist,
            */ 
            let self=this;
            let {assData,checkedArray,childAssData}=self.state;
            let {pretentAssData}=nextProp;
        if(nextProp.showOrHide&&childAssData!=pretentAssData){              
            childAssData=pretentAssData;
            checkedArray=pretentAssData.checkedArray;
            self.setState({
                checkedArray
            })
            if(pretentAssData.assid && pretentAssData.assid != '[]'){ 
                self.setState({
                    assData:pretentAssData.assData,
                    childAssData
                })
            } else {
                assData=[];
                //请求辅助核算数据
                let url = '/nccloud/gl/voucher/queryAllAssItem.do';
                let queryData = {
                    pk_accountingbook: pretentAssData.pk_accountingbook
                };
                ajax({
                    url:url,
                    data:queryData,
                    success: function(response){
                        const { success } = response;
                        //渲染已有账表数据遮罩
                        if (success) {
                            if(response.data){
                                if(response.data.assvo.length>0){
                                    response.data.assvo.map((item,index)=>{
                                        item.key=index;
                                        let obj={
                                            key:index,
                                            "checktypecode":item.code,
                                            "checktypename" :item.name,
                                            "pk_Checktype": item.pk_accassitem,
                                            "refCode":item.refCode?item.refCode:item.code,
                                            "refnodename":item.refnodename,
                                            "pk_accassitem":item.pk_accassitem,
                                            "m_classid":item.classid,
                                            "classid":item.classid,
                                            "pk_defdoclist":item.classid,
                                            "pk_accountingbook":childAssData.pk_accountingbook
                                        }
                                        assData.push(obj);
                                    })
                                    
                                }
                            }
                            childAssData.assData=assData;
                            self.setState({
                                assData,childAssData
                            })
                        }   
                    }
                });
            }
        }
    }
    

    //表格操作根据key寻找所对应行
	findByKey(key, rows) {
		let rt = null;
		let self = this;
		rows.forEach(function(v, i, a) {
			if (v.key == key) {
				rt = v;
			}
		});
		return rt;
	}

    close() {
        this.props.handleClose();
    }

    confirm = () =>{
        let sendData = {};
        let assid='',assname='';
        let { SelectedAssData,checkedArray,listItem,assData,childAssData } = this.state;
        SelectedAssData=[];//清空
        for(var i = 0; i < checkedArray.length; i++){
            if(checkedArray[i]==true){
                SelectedAssData.push(assData[i]);
                assname += '【'+ assData[i].checktypename + ':'+ (assData[i].checkvaluename?assData[i].checkvaluename:'~')+'】';
            }
        }
        sendData = {
            data:SelectedAssData,
            assname:assname,
            checkedArray,
            assData
        };
        this.props.onConfirm(sendData);
    }
    //全选
    onAllCheckChange(){
        let self = this;
        let checkedArray = [];
        let {assData} = self.state;
        let selIds = [];
        for (var i = 0; i < assData.length; i++) {
          checkedArray[i] = !self.state.checkedAll;
        }
        self.setState({
          checkedAll: !self.state.checkedAll,
          checkedArray: checkedArray,
        });
      };
      //单选
      onCheckboxChange(text, record, index){
        let self = this;
        let allFlag = false;
        let checkedArray = self.state.checkedArray.concat();
        checkedArray[index] = !self.state.checkedArray[index];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
          if (!checkedArray[i]) {
            allFlag = false;
          } else {
            allFlag = true;
          }
        }
        self.setState({
          checkedAll: allFlag,
          checkedArray: checkedArray,
        });
      };
      
      renderColumnsMultiSelect(columns) {
        const {checkedArray, assData} = this.state;
        const { multiSelect } = this.props;
        let select_column = {};
        let indeterminate_bool = false;
        // let indeterminate_bool1 = true;
        if (multiSelect && multiSelect.type === "checkbox") {
          let i = checkedArray.length;
          while(i--){
              if(checkedArray[i]){
                indeterminate_bool = true;
                break;
              }
          }
          let checkedlen = 0, allFlag = '';
          for (var j = 0; j < checkedArray.length; j++) {
            if (checkedArray[j]) {
                checkedlen ++;
            }
          }
          if (checkedlen == assData.length) {
            allFlag = true;
          } else {
            allFlag = false;
          }
          let defaultColumns = [
            {
              title: (
                <Checkbox
                  className="table-checkbox"
                  checked={allFlag}
                  indeterminate={indeterminate_bool&&!allFlag}
                  onChange={this.onAllCheckChange.bind(this)}
                />
              ),
              key: "checkbox",
              dataIndex: "checkbox",
              width: "60",
              render: (text, record, index) => {
                return (
                  <Checkbox
                    className="table-checkbox"
                    checked={this.state.checkedArray[index]}
                    onChange={this.onCheckboxChange.bind(this, text, record, index)}
                  />
                );
              }
            }
          ];
          columns = defaultColumns.concat(columns);
        }
        return columns;
      }

    render() {
        let{showOrHide,pretentAssData}=this.props;
        let { loadData,assData} =this.state;
        let columnsldad;
        const dateInputPlaceholder = this.state.json['publiccomponents-000000'];/* 国际化处理： 选择日期*/
        let columns10=[
            {
              title: this.state.json['publiccomponents-000001'],/* 国际化处理： 核算类型编码*/
              dataIndex: "checktypecode",
              key: "checktypecode",
              width: '100',
              render: (text, record, index) => {
				return <span>{record.checktypecode}</span>;
			    }
            },
            {
                title: this.state.json['publiccomponents-000002'],/* 国际化处理： 核算类型名称*/
                dataIndex: "checktypename",
                key: "checktypename",
                width: '180',
                render: (text, record, index) => {
                  return <span>{record.checktypename}</span>;
                  }
              },
            {
              title: this.state.json['publiccomponents-000003'],/* 国际化处理： 核算内容*/
              dataIndex: "checkvaluename",
              key: "checkvaluename",
              width: '200',
                render: (text, record, index) => {
                    let { assData,childAssData } =this.state;
                    let defaultValue=[];
                    if(assData[index]['checkvaluename']){                           
                        assData[index]['checkvaluename'].map((item,_index)=>{
                            defaultValue[_index]={ refname: item, refpk:'' };
                        })
                        assData[index]['pk_Checkvalue'].map((item,_index)=>{
                            defaultValue[_index].refpk=item;
                        })
                    }else{
                        defaultValue=[{refname:"",refpk:""}];
                    }
                    if(record.refnodename){
                        let referUrl= record.refnodename+'.js'; 
                        let config={
                            "pk_org": childAssData.pk_org,
                            "pk_unit": childAssData.pk_org,
                            "pk_defdoclist": record.pk_defdoclist,
                            "pk_accountingbook": childAssData.pk_accountingbook,
                            "date": childAssData.prepareddate,
                            "pk_accasoa": childAssData.pk_accasoa,
                            "classid": record.classid,
                            "assvo": JSON.stringify(assData),
                            "isDataPowerEnable": 'Y',
                            "DataPowerOperationCode" : 'fi'
                            // "GridRefActionExt": 'nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder',
                            // "TreeRefActionExt": 'nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder'
                        }
                        if(!this.state[record.pk_accassitem]){
                            {createScript.call(this,referUrl,record.pk_accassitem)}
                            return <div />
                        }else{
                            if(record.classid=='b26fa3cb-4087-4027-a3b6-c83ab2a086a9'||record.classid=='40d39c26-a2b6-4f16-a018-45664cac1a1f'){//部门，人员
                                return (
                                    <div className='period-container'>
                                    <div>
                                    {this.state[record.pk_accassitem]?(this.state[record.pk_accassitem])(
                                        {
                                            value:defaultValue,
                                            isShowUnit:true,
                                            unitProps:{
                                                refType: 'tree',
                                                refName: this.state.json['publiccomponents-000011'],/* 国际化处理： 业务单元*/
                                                refCode: 'uapbd.refer.org.BusinessUnitTreeRef',
                                                rootNode:{refname:this.state.json['publiccomponents-000011'],refpk:'root'},/* 国际化处理： 业务单元*/
                                                placeholder:this.state.json['publiccomponents-000011'],/* 国际化处理： 业务单元*/
                                                queryTreeUrl: '/nccloud/uapbd/org/BusinessUnitTreeRef.do',
                                                treeConfig:{name:[this.state.json['publiccomponents-000012'], this.state.json['publiccomponents-000013']],code: ['refcode', 'refname']},/* 国际化处理： 编码,名称*/
                                                isMultiSelectedEnabled: false,
                                                //unitProps:unitConf,
                                                isShowUnit:false
                                            },
                                            unitCondition:{
                                                pk_financeorg:childAssData.pk_org,
                                                'TreeRefActionExt':'nccloud.web.gl.ref.OrgRelationFilterRefSqlBuilder'
                                            },
                                            isMultiSelectedEnabled:true,
                                            "unitValueIsNeeded":false,
                                            "isShowDimission":true,
                                            queryCondition:(obj) => {
                                                if(obj){
                                                if(obj.refType=='grid'){
                                                    config.GridRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }else if(obj.refType=='tree'){
                                                    config.TreeRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }else if(obj.refType=='gridTree'){
                                                    config.GridRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }}
                                                if(record.classid&&record.classid.length==20){//classid的长度大于20的话过滤条件再加一个pk_defdoclist
                                                    return config
                                                }else{
                                                    if(record.classid=='40d39c26-a2b6-4f16-a018-45664cac1a1f'){//人员
                                                        config.isShowDimission=true;
                                                        config.busifuncode="all";
                                                        return config
                                                    }else{
                                                        return config 
                                                    }
                                                    
                                                }   
                                            },
                                            onChange:(v)=>{
                                                let { assData } =this.state;
                                                let originData = this.findByKey(record.key, assData);
                                                let refnameArr=[],refpkArr=[],refcodeArr=[];
                                                if (originData) {
                                                    v.map((arr,index)=>{
                                                            refnameArr.push(arr.refname);
                                                            refpkArr.push(arr.refpk);
                                                            refcodeArr.push(arr.refcode);
                                                    
                                                    })    
                                                    originData.checkvaluename = refnameArr;
                                                    originData.pk_Checkvalue = refpkArr;
                                                    originData.checkvaluecode=refcodeArr;
                                                }
                                                childAssData.assData=assData; 
                                                this.setState({
                                                assData,childAssData
                                                })
                                            }
                                        }):<div />}
                                    </div>
                                    </div>);
                            }else{
                                let isProfitCenter = record.classid == 'eca72cac-085b-4796-b433-1b17b754574c';
                                return (
                                <div className='period-container'>
                                <div>
                                {this.state[record.pk_accassitem]?(this.state[record.pk_accassitem])(
                                    {
                                        value:defaultValue,
                                        isMultiSelectedEnabled:true,
                                        queryCondition:(obj) => {
                                            if(obj){
                                                if(obj.refType=='grid'){
                                                    config.GridRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }else if(obj.refType=='tree'){
                                                    config.TreeRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }else if(obj.refType=='gridTree'){
                                                    config.GridRefActionExt='nccloud.web.gl.ref.AccAssRuleCtrlSqlBuilder';
                                                }
                                            }
                                            if(isProfitCenter){
                                                config.financeorg = config.pk_org;
                                            }
                                            return config  
                                        },
                                        onChange:(v)=>{
                                            let { assData } =this.state;
                                            let originData = this.findByKey(record.key, assData);
                                            let refnameArr=[],refpkArr=[],refcodeArr=[];
                                            if (originData) {
                                                v.map((arr,index)=>{
                                                        refnameArr.push(arr.refname);
                                                        refpkArr.push(arr.refpk);
                                                        refcodeArr.push(arr.refcode);
                                                
                                                })    
                                                originData.checkvaluename = refnameArr;
                                                originData.pk_Checkvalue = refpkArr;
                                                originData.checkvaluecode=refcodeArr;
                                            }
                                            childAssData.assData=assData; 
                                            this.setState({
                                            assData,childAssData
                                            })
                                        }
                                    }):<div />}
                                </div>
                                </div>
                                );
                            }
                        }
                    }else{//不是参照的话要区分日期、字符、数值
                        if(record.classid=='BS000010000100001033'){//日期
                            return(
                                <div className='period-container'>
                                <DatePicker
                                    //name={item.itemKey}
                                    format={timeFormat}
                                    type="customer"
                                    isRequire={true}
                                    placeholder={dateInputPlaceholder}
                                    value={defaultValue[0].refname}
                                    onChange={(v) => {
                                        let { assData } =this.state;
                                        let originData = this.findByKey(record.key, assData);
                                        if (originData) {
                                            let assArr=[];
                                            assArr.push(v);
                                            originData.checkvaluename = assArr;
                                            originData.pk_Checkvalue =assArr;
                                            originData.checkvaluecode=assArr;
                                        }
                                        childAssData.assData=assData; 
                                        this.setState({
                                        assData,childAssData
                                        })
                                    }}
                                    
                                    />
                                </div>
                            )
                        }else if(record.classid=='BS000010000100001034'){//日期
                            return(
                                <div className='period-container'>
                                <DatePicker
                                    //name={item.itemKey}
                                    showTime={true}
                                    format={timeFormat}
                                    type="customer"
                                    isRequire={true}
                                    placeholder={dateInputPlaceholder}
                                    value={defaultValue[0].refname}
                                    onChange={(v) => {
                                        let { assData } =this.state;
                                        let originData = this.findByKey(record.key, assData);
                                        if (originData) {
                                            let assArr=[];
                                            assArr.push(v);
                                            originData.checkvaluename = assArr;
                                            originData.pk_Checkvalue =assArr;
                                            originData.checkvaluecode=assArr;
                                        }
                                        childAssData.assData=assData; 
                                        this.setState({
                                        assData,childAssData
                                        })
                                    }}
                                    />
                                </div>
                            )
                        }else if(record.classid=='BS000010000100001031'){//数值
                            return(
                                <div className='period-container'>
                                <NCNumber
                                    scale={2}
                                    value={defaultValue[0].refname}
                                    placeholder={this.state.json['publiccomponents-000004']}/* 国际化处理： 请输入数字*/
                                    onChange={(v)=>{
                                        let { assData } =this.state;
                                        let originData = this.findByKey(record.key, assData);
                                        if (originData) {
                                            let assArr=[];
                                            assArr.push(v);
                                            originData.checkvaluename = assArr;
                                            originData.pk_Checkvalue =assArr;
                                            originData.checkvaluecode=assArr;
                                        }
                                        childAssData.assData=assData; 
                                        this.setState({
                                        assData,childAssData
                                        })
                                    }}
                                />
                                </div>
                            )
                        }else if(record.classid=='BS000010000100001032'){//布尔
                            return(
                                <div className='period-container'>
                                    <div>
                                    <SelectItem name={record.checktypecode}
                                        defaultValue={defaultValue[0].refname} 
                                        items = {
                                            () => {
                                                return ([{
                                                    label: this.state.json['publiccomponents-000005'],/* 国际化处理： 是*/
                                                    value: 'Y'
                                                }, {
                                                    label: this.state.json['publiccomponents-000006'],/* 国际化处理： 否*/
                                                    value: 'N'
                                                }]) 
                                            }
                                        }
                                        onChange={(v)=>{
                                            let { assData } =this.state;
                                            let originData = this.findByKey(record.key, assData);
                                            if (originData) {
                                                let assArr=[];
                                                assArr.push(v);
                                                originData.checkvaluename = assArr;
                                                originData.pk_Checkvalue =assArr;
                                                originData.checkvaluecode=assArr;
                                            }
                                            childAssData.assData=assData; 
                                            this.setState({
                                            assData,childAssData
                                            })
                                        }}
                                    />
                                </div>
                                </div>
                            )
                        }else{//字符
                            return(
                                <div className='period-container'>
                                <div className='period-char'>
                                <FormControl
                                    value={defaultValue[0].refname}
                                    onChange={(v)=>{
                                        let { assData } =this.state;
                                        let originData = this.findByKey(record.key, assData);
                                        if (originData) {
                                            let assArr=[];
                                            assArr.push(v);
                                            originData.checkvaluename = assArr;
                                            originData.pk_Checkvalue =assArr;
                                            originData.checkvaluecode=assArr;
                                        }
                                        childAssData.assData=assData; 
                                        this.setState({
                                        assData,childAssData
                                        })
                                    }}
                                />
                                </div>
                                </div>
                            )
                        }
                        
                    }
                }
            }
        ];
        if(pretentAssData.checkboxShow){//复选框显示true
            columnsldad = this.renderColumnsMultiSelect(columns10);
        }else{
            columnsldad=columns10;
        }
        const emptyFunc = () => <span>{this.state.json['publiccomponents-000007']}！</span>/* 国际化处理： 这里没有数据*/
        return (
            <div className="fl">
                <Modal
                    className={'msg-modal'}
                    backdrop={'static'}
                    show={showOrHide }
                    //show={true}
                    // backdrop={ this.state.modalDropup }
                    onHide={ this.close }
                    size = {'md'}
                    animation={true}
                    >
                    <Modal.Header closeButton>
                        <Modal.Title>{this.state.json['publiccomponents-000014']}</Modal.Title>{/* 国际化处理： 辅助核算对话框*/}
                    </Modal.Header >
                    <Modal.Body >
                        <Table
                            columns={columnsldad}
                             data={assData}
                             inModal={true}
                            emptyText={emptyFunc}
                            addBlankCol = {false} //不添加空白列
                            scroll={{x:true, y: 200 }}
                        />
                    </Modal.Body>
                    <Modal.Footer>
                        <Button colors="primary" onClick={ this.confirm }> {this.state.json['publiccomponents-000009']} </Button>{/* 国际化处理： 确定*/}
                        <Button onClick={ this.close }> {this.state.json['publiccomponents-000015']} </Button>{/* 国际化处理： 关闭*/}
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }
}
AssidModal.defaultProps = defaultProps12;
// export default function (props = {}) {
//     var conf = {
//     };

//     return <AssidModal {...Object.assign(conf, props)} />
// }
